// 公共方法

/**
 * 生成随机不重复的字符串 
 * @param len 长度
 * @returns 
 */
export function randomStr(len = 6) {
    return Math.random().toString(36).substr(2, len)
}


/**
 * 设置localStorage  
 */
export function setLocal(key: string, value: string): void {
    localStorage.setItem(key, value)
}

/**
 * 获取localStorage  
 */
export function getLocal(key: string): string {
    return localStorage.getItem(key)
}

/**
 * 存储管理类
 */
export class Store<T> {
    private key: string
    constructor(key) {
        this.key = key || randomStr()
    }

    set(value: Object | string): void {
        if (typeof value === 'object') {
            const str = JSON.stringify(value)
            setLocal(this.key, str)
            return
        }
        setLocal(this.key, value)
    }

    get(): string | object {
        const value = getLocal(this.key)
        try {
            return JSON.parse(value)
        } catch (e) {
            return value
        }
    }
}